package com.roncoo.education.oauth.service;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.security.PermitAll;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.csp.sentinel.util.StringUtil;
import com.roncoo.education.course.feign.interfaces.IFeignExperimentScore;
import com.roncoo.education.course.feign.interfaces.score.CallbackExperimentScoreReportReq;
import com.roncoo.education.course.feign.interfaces.score.CallbackExperimentScoreReq;
import com.roncoo.education.course.feign.interfaces.score.UploadResp;
import com.roncoo.education.course.feign.interfaces.score.constant.UploadAttachmentCodeConst;
import com.roncoo.education.course.feign.interfaces.score.constant.UploadScoreCodeConst;
import com.roncoo.education.course.feign.interfaces.vo.ExperimentViewVO;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
 
/**
 * @author 千城丶Y
 * @className : IndexController
 * @PACKAGE_NAME : com.bjpowernode.controller
 * @date : 2022/9/21 23:59
 * @Description TODO
 */
@Api(tags = "ADMIN-实验分数")
@RestController
@RequiredArgsConstructor
@RequestMapping("/oauth/api/v1")
public class UploadController {

    @NotNull
    private final IFeignExperimentScore biz;
    
    @Autowired
    private IFeignExperimentScore experimentScore;    
 
    @GetMapping("/hello")
    @PreAuthorize("#oauth2.hasScope('callback:score')") //
    public String hello(){
        return "hello!";
    }
    
    @GetMapping("/hello1")
    @PreAuthorize("permitAll") //
    public String hello1(){
        return "hello1!";
    }
    
    @GetMapping("/hello2")
    @PreAuthorize("#oauth2.hasScope('callback:score2')") //
    public String hello2(){
        return "hello2!";
    }

    @GetMapping("/hello3")
    @PermitAll
    public String hello3(){
        return "hello3!";
    }
    
    @GetMapping("/hello4")
    @PreAuthorize("hasRole('ROLE_ANONYMOUS')") //
    public String hello4(){
        return "hello4!";
    }
    
    @GetMapping("/hello5")
    public String hello5(){
        return "hello5!";
    }    
    
 
    @ApiOperation(value = "实验分数添加", notes = "实验分数添加")
    @RequestMapping(value = "data_upload", method = {RequestMethod.GET, RequestMethod.POST})
    @PreAuthorize("#oauth2.hasScope('callback:score')")
    public Object dataUpload(@RequestBody @Valid CallbackExperimentScoreReq req, BindingResult bindingResult) {
    	Map<String, Object> ret = new HashMap<String, Object>();
    	
    	if (bindingResult.hasErrors()) {
    		String msg = bindingResult.getAllErrors().get(0).getDefaultMessage();
    		
    		if (msg.startsWith("数据错误")) {
    			ret.put("code", UploadScoreCodeConst.code_6);
    			ret.put("msg", msg);
    		} else if (msg.startsWith("实验步骤数据错误")) {
    			String field = ((DefaultMessageSourceResolvable) bindingResult.getAllErrors().get(0).getArguments()[0]).getDefaultMessage();
    			String seq = find(field);
    			msg = msg.replaceAll("seq", seq);
    			ret.put("code", UploadScoreCodeConst.code_11);
    			ret.put("msg", msg);
    		} else {
    			ret.put("code", UploadScoreCodeConst.code_999);
    			ret.put("msg", msg);
    		}
			
			return ret;
    	}

    	UploadResp resp = biz.uploadScore(req);
    	if (resp.getId() != null) {
    		ret.put("id", resp.getId());
    	}
    	if (resp.getMsg() != null) {
    		ret.put("msg", resp.getMsg());
    	}
    	ret.put("code", resp.getCode());
    	return ret;
    }
    
    @ApiOperation(value = "上传附件", notes = "服务端上传图片接口，只支持图片格式")
    @RequestMapping(value = "attachment_upload", method = {RequestMethod.GET, RequestMethod.POST})
    @PreAuthorize("#oauth2.hasScope('callback:score')")
    public Object uploadAttachment(@RequestParam String appid,
			@RequestParam String originId,
			@RequestParam String filename,
			@RequestParam String title,
			@RequestParam(required = false) String remarks,
			@RequestBody String contents, 
			@RequestParam(value = "file", required = false) MultipartFile file) {
    	Map<String, Object> ret = new HashMap<String, Object>();
    	
    	if (StringUtils.isBlank(originId) || StringUtils.isBlank(appid) || StringUtils.isBlank(filename) || filename.indexOf(".") == 0 || filename.endsWith(".")) {
			ret.put("code", UploadAttachmentCodeConst.code_1);
			ret.put("msg", UploadAttachmentCodeConst.code_1_msg);
			return ret;
    	}    	
    	
    	CallbackExperimentScoreReportReq req = new CallbackExperimentScoreReportReq();
    	req.setAppid(appid);
    	req.setOriginId(originId);
    	req.setFilename(filename);
    	req.setTitle(title);
    	req.setRemarks(remarks);
    	req.setContents(contents);
        
    	UploadResp resp = biz.uploadAttachment(req, file);
    	if (resp.getId() != null) {
    		ret.put("id", resp.getId());
    	}
    	if (resp.getMsg() != null) {
    		ret.put("msg", resp.getMsg());
    	}
    	ret.put("code", resp.getCode());
    	return ret;
    }
    
    private static String find(String source) {
        String input = source;
        Pattern p = Pattern.compile("\\d+");
        Matcher m = p.matcher(input);
 
        if (m.find()) {
        	return m.group();
        };
        return StringUtil.EMPTY;
    }
    
}